<template>
	<view v-if="isPageShow" @click.prevent.stop class="layout-main" :class="{ transform: isTransform }">
		<view
			class="layout-main-content"
			:style="{
				backgroundImage: 'url(' + bgImageUrl + ')'
			}"
		>
			<text>{{ countdownTime }}</text>
		</view>
	</view>
</template>

<script>
import moment from 'dayjs';
import { debounce } from 'lodash';
import { defaultImageUrl } from '@/utils';
import { liveShowDateFormat } from '@/utils/common';

const bgImageUrl = Object.freeze(`${defaultImageUrl}icon/img_spxq_xf.png`);

const oneDayTime = 1000 * 60 * 60 * 24;

export default {
	name: 'Countdown',

	props: {
		isExpire: {
			type: Number,
			default: 1 // 是否在有效期内 0 -在; 1 -不在
		},

		endTime: {
			type: Number
		},

		nowTime: {
			type: Number
		},

		endTimeStr: {
			type: String
		}
	},

	data() {
		return {
			bgImageUrl,

			intervalId: null,
			countdown: undefined,

			isTransform: false,
			debounced: debounce((e) => {
				this.isTransform = false;
			}, 350)
		};
	},

	watch: {
		endTime() {
			const { nowTime, endTime, isPageShow, isOneDay } = this;

			if (nowTime && endTime && isPageShow) {
				const diffTime = moment(endTime).diff(nowTime);

				if (isOneDay && !this.countdown) {
					this.changeCountdown(diffTime);
				}
			}
		}
	},

	computed: {
		isOneDay() {
			const { endTime, nowTime } = this;
			const diffTime = moment(endTime).diff(nowTime);

			return diffTime <= oneDayTime;
		},

		isPageShow() {
			const { isExpire, endTime, nowTime } = this;
			// const diffTime = moment(endTime).diff(nowTime);

			return !isExpire;
			// return !isExpire && diffTime <= oneDayTime;
		},

		countdownTime() {
			const { countdown, isOneDay, endTimeStr } = this;

			if (isOneDay) {
				return liveShowDateFormat(countdown);
			}

			return endTimeStr;
		}
	},

	methods: {
		changePageScroll() {
			if (this.isPageShow) {
				this.debounced();
				this.isTransform = true;
			}
		},
		changeCountdown(value) {
			this.countdown = value;

			this.intervalId = setInterval((e) => {
				if (this.countdown < 1000) {
					clearInterval(this.intervalId);

					this.$emit('changeisExpire');
					return;
				}

				this.countdown = this.countdown - 1000;
			}, 1000);
		}
	},

	destroyed() {
		clearInterval(this.intervalId);
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.layout-main {
	position: fixed;
	right: 10rpx;
	z-index: 999;
	transition: all 0.3s;
	backface-visibility: hidden;
	transform: translateZ(0) translate3d(0, 0, 0);
	@include Db_iosPositionBottomDistance(150rpx);

	&-content {
		width: 164rpx;
		height: 164rpx;
		background-repeat: no-repeat;
		background-size: 100% 100%;

		position: relative;

		text {
			position: absolute;
			left: 0;
			right: 0;
			height: 34rpx;
			line-height: 34rpx;
			bottom: 24rpx;
			text-align: center;
			color: #fff;
			font-size: 29rpx;
			font-weight: bold;
		}
	}

	&.transform {
		opacity: 0.3;
		transform: translateX(135rpx);
	}
}
</style>
